﻿using System;

namespace Rogan.Utility.Common
{
    public class ConvertHelper
    {
        public static int ObjToInt(object obj)
        {
            if (obj == null)
            {
                return 0;
            }
            if (obj.Equals(DBNull.Value))
            {
                return 0;
            }
            int result;
            if (int.TryParse(obj.ToString(), out result))
            {
                return result;
            }
            return 0;
        }
        public static bool ObjToBool(object obj)
        {
            bool flag;
            return obj != null && !obj.Equals(DBNull.Value) && bool.TryParse(obj.ToString(), out flag) && flag;
        }
        public static int? ObjToIntNull(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            if (obj.Equals(DBNull.Value))
            {
                return null;
            }
            return ObjToInt(obj);
        }
        public static string ObjToStr(object obj)
        {
            if (obj == null)
            {
                return "";
            }
            if (obj.Equals(DBNull.Value))
            {
                return "";
            }
            return Convert.ToString(obj);
        }
        public static decimal ObjToDecimal(object obj)
        {
            if (obj == null)
            {
                return 0m;
            }
            if (obj.Equals(DBNull.Value))
            {
                return 0m;
            }
            decimal result;
            try
            {
                result = Convert.ToDecimal(obj);
            }
            catch
            {
                result = 0m;
            }
            return result;
        }
        public static decimal? ObjToDecimalNull(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            if (obj.Equals(DBNull.Value))
            {
                return null;
            }
            return ObjToDecimal(obj);
        }
        public static DateTime? ObjToDateNull(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            DateTime? result;
            try
            {
                result = Convert.ToDateTime(obj);
            }
            catch
            {
                result = null;
            }
            return result;
        }
    }
}
